package com.movitech.mobile.cz.base.sys.bizservice.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.movitech.mobile.cz.base.bizconfig.service.impl.MessageUtilService;
import com.movitech.mobile.cz.base.common.license.LicenseUtil;
import com.movitech.mobile.cz.base.common.redis.RedisDBHelper;
import com.movitech.mobile.cz.base.common.util.CodeUtil;
import com.movitech.mobile.cz.base.common.util.CommonConstants;
import com.movitech.mobile.cz.base.common.util.StringUtils;
import com.movitech.mobile.cz.base.common.utils.JwtUtils;
import com.movitech.mobile.cz.base.modules.config.CommentConfigEnum;
import com.movitech.mobile.cz.base.modules.controller.RestReturnResult;
import com.movitech.mobile.cz.base.supplier.entity.SSuppliers;
import com.movitech.mobile.cz.base.supplier.service.SCommentConfigService;
import com.movitech.mobile.cz.base.supplier.service.SSuppliersService;
import com.movitech.mobile.cz.base.sys.bizservice.LoginAndPwdService;
import com.movitech.mobile.cz.base.sys.bizvo.UserChangeRequestVO;
import com.movitech.mobile.cz.base.sys.bizvo.UserRequestVO;
import com.movitech.mobile.cz.base.sys.bizvo.UserResponseVO;
import com.movitech.mobile.cz.base.sys.entity.SysUser;
import com.movitech.mobile.cz.base.sys.service.SysUserService;
import com.movitech.mobile.cz.base.util.UserUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.RenderedImage;
import java.util.Date;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service("loginAndPwdService")
@Transactional
public class LoginAndPwdServiceImpl implements LoginAndPwdService {

	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SSuppliersService sSuppliersService;
	@Autowired
	RedisDBHelper<String, String> redisDBHelper;

	@Autowired
	private SCommentConfigService sCommentConfigService;

	@Autowired
	private MessageUtilService messageUtilService;


	@Value("${zuul.jwt.token.ttl}")
	private Long jwtTokenTTL;

	@Value("${zuul.jwt.refresh.token.ttl}")
	private Long jwtRefreshTokenTTL;
	/***
	 * 采购外网平台登录
	 * @param userRequestVo
	 * @return
	 */
	@Override
	public RestReturnResult restLogin(UserRequestVO userRequestVo, HttpServletResponse response, HttpServletRequest request) {
		RestReturnResult restResult=RestReturnResult.error();
		try {
			LicenseUtil.INSTANCE.validate();
			SysUser sysUser=sysUserService.getSysUserByUserName(userRequestVo.getUserName());
			if(sysUser==null||sysUser.getUserType()==null||sysUser.getUserType()==CommonConstants.INNER_USER){
				restResult=new RestReturnResult(CommonConstants.FAIL,"用户名不存在");
			}else {
				if(StringUtils.isEmpty(userRequestVo.getCodeKey())){
					restResult=new RestReturnResult(CommonConstants.FAIL,"验证码错误");
					return restResult;
				}
				String piccode=redisDBHelper.hashGet(CommonConstants.PICCODE+userRequestVo.getCodeKey(),userRequestVo.getCodeKey());
				if(StringUtils.isNotEmpty(piccode)&&StringUtils.isNotEmpty(userRequestVo.getVerificationCode())){
					if(!piccode.toUpperCase().equals(userRequestVo.getVerificationCode().toUpperCase())){
						restResult=new RestReturnResult(CommonConstants.FAIL,"验证码错误");
						return restResult;
					}
				}else{
					restResult=new RestReturnResult(CommonConstants.FAIL,"验证码错误");
					return restResult;
				}
				if(CommonConstants.YES_LOGIN.equals(sysUser.getLoginFlag())){
					if (sysUser.getPassword().equals(userRequestVo.getPassword())
							|| sysUser.getPassword().equals(DigestUtils.md5Hex(userRequestVo.getPassword()))) {
						restResult=new RestReturnResult(CommonConstants.SUCCESS,"登录成功");
						UserResponseVO userResponseVO=new UserResponseVO();
						if(StringUtils.isNotEmpty(sysUser.getId())){
								EntityWrapper objectEntityWrapper = new EntityWrapper<>();
								SSuppliers wrapperSupplier=new SSuppliers();
								wrapperSupplier.setSysUserId(sysUser.getId());
								wrapperSupplier.setDelFlag(CommonConstants.DEL_FLAG_NORMAL);
								objectEntityWrapper.setEntity(wrapperSupplier);
								SSuppliers sSuppliers=sSuppliersService.selectOne(objectEntityWrapper);
								userResponseVO.setUserId(sysUser.getId());
								userResponseVO.setUserName(sysUser.getLoginName());
								if(sSuppliers!=null){
									userResponseVO.setSuppliersId(sSuppliers.getId());
									userResponseVO.setCompanyName(sSuppliers.getCompanyName());
								}else{
									restResult=new RestReturnResult(CommonConstants.FAIL,"账户不存在或者被禁用！");
									return restResult;
								}
							}
						restResult.setData(userResponseVO);
						response.setHeader("token", JwtUtils.createJWT(userResponseVO.toString(), jwtTokenTTL));
						response.setHeader("refresh_token", JwtUtils.createJWT(userResponseVO.toString(), jwtRefreshTokenTTL));
					} else {
						restResult=new RestReturnResult(CommonConstants.FAIL,"账号或密码错误");
					}
				}else{
					restResult=new RestReturnResult(CommonConstants.FAIL,"该用户已禁用");
				}
			}
		}catch (Exception e){
			e.printStackTrace();
			restResult=RestReturnResult.error();
		}
		return restResult;
	}

	/***
	 * 采购外网平台忘记密码
	 * @param userRequestVo
	 * @return
	 */
	@Override
	public RestReturnResult restFindPassword(UserRequestVO userRequestVo) {
		RestReturnResult restResult=RestReturnResult.error();
		try {
			LicenseUtil.INSTANCE.validate();
			SysUser sysUser=sysUserService.getSysUserByUserName(userRequestVo.getUserName());
			if(sysUser==null||sysUser.getUserType()==null||sysUser.getUserType()==CommonConstants.INNER_USER){
				restResult=new RestReturnResult(CommonConstants.FAIL,"用户名不存在");
			}else {
				String piccode=redisDBHelper.hashGet(CommonConstants.SMSCODE+userRequestVo.getUserName(),userRequestVo.getUserName());
				if(StringUtils.isNotEmpty(piccode)&&StringUtils.isNotEmpty(userRequestVo.getVerificationCode())){
					if(!piccode.toUpperCase().equals(userRequestVo.getVerificationCode().toUpperCase())){
						restResult=new RestReturnResult(CommonConstants.FAIL,"验证码错误");
						return restResult;
					}
				}else{
					restResult=new RestReturnResult(CommonConstants.FAIL,"验证码错误");
					return restResult;
				}
				sysUser.setPassword(userRequestVo.getPassword());
				boolean result=sysUserService.updateById(sysUser);
				if(result){
					restResult=new RestReturnResult(CommonConstants.SUCCESS,"修改成功");
				}else{
					restResult=new RestReturnResult(CommonConstants.FAIL,"系统错误");
				}
			}
		}catch (Exception e){
			e.printStackTrace();
			restResult=RestReturnResult.error();
		}
		return restResult;
	}

	@Override
	public RestReturnResult changePassword(HttpServletRequest request, HttpServletResponse response,UserChangeRequestVO userChangeRequestVO) {
				RestReturnResult restResult = RestReturnResult.error();
				String userId= UserUtils.getOuterCurrentUserId();
		LicenseUtil.INSTANCE.validate();
				if(userId!=null){
					SysUser sysUser=sysUserService.selectById(userId);
					if(sysUser!=null){
						if (sysUser.getPassword().equals(userChangeRequestVO.getPasswordOld())
								|| sysUser.getPassword().equals(DigestUtils.md5Hex(userChangeRequestVO.getPasswordOld()))) {
							sysUser.setPassword(userChangeRequestVO.getPasswordNew());
							sysUser.setUpdateDate(new Date());
							sysUser.setUpdateBy(userId);
							if(sysUserService.updateById(sysUser)){
								restResult = RestReturnResult.success();
							}else{
								RestReturnResult.error();
							}
						}else{
							restResult.setMsg("原密码错误");
						}
					}else{
						restResult.setMsg("用户不存在");
					}
				}else{
					restResult.setMsg("未登录");
				}
				return restResult;
	}

	@Override
	public RestReturnResult sendSmsCode(String phone) {
		String verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);//短信验证码
//		String verifyCode = "123456";//短信验证码
//		String smsValue=sCommentConfigService.getValueByCode(CommentConfigEnum.SMSCODE.getCode());
//		smsValue=smsValue.replace("[0]",verifyCode);
//		smsValue=smsValue.replace("[1]","5分钟");
//		boolean result = smsUtil.sendSms(phone,smsValue);
		String configValue=sCommentConfigService.getValueByCode(CommentConfigEnum.SMSCODE.getCode());
		boolean result=messageUtilService.messageSendSyn(configValue,phone,new String[]{verifyCode,"1小时"});
		if(result){
			// 将验证码保存到redis中。
			redisDBHelper.hashPut(CommonConstants.SMSCODE+phone, phone, verifyCode);
			redisDBHelper.expire(CommonConstants.SMSCODE+phone,60*60, TimeUnit.SECONDS);
			System.out.println("验证码redis>>>>>>"+verifyCode);
			return RestReturnResult.success();
		}else{
			return RestReturnResult.error();
		}
	}


	@Override
	public RestReturnResult getGraphicCode(HttpServletRequest req, HttpServletResponse resp,String phone) {
		try {
			LicenseUtil.INSTANCE.validate();
			// 调用工具类生成的验证码和验证码图片
			Map<String, Object> codeMap = CodeUtil.generateCodeAndPic();

			// 将四位数字的验证码保存到Session中。
//		HttpSession session = req.getSession();
//		session.setAttribute("code", codeMap.get("code").toString());


			// 将四位数字的验证码保存到redis中。
			redisDBHelper.hashPut(CommonConstants.PICCODE+phone, phone, codeMap.get("code").toString().toUpperCase());
			redisDBHelper.expire(CommonConstants.PICCODE+phone,5*60, TimeUnit.SECONDS);

			// 禁止图像缓存。
			resp.setHeader("Pragma", "no-cache");
			resp.setHeader("Cache-Control", "no-cache");
			resp.setDateHeader("Expires", -1);

			resp.setContentType("image/jpeg");

			// 将图像输出到Servlet输出流中。
			ServletOutputStream sos;
			sos = resp.getOutputStream();
			ImageIO.write((RenderedImage) codeMap.get("codePic"), "jpeg", sos);
			sos.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return RestReturnResult.error();
		}
		return RestReturnResult.success();
	}

}
